package xml;

import assignment.Skill;
import assignment.Person;
import assignment.Task
import assignment.*;
import groovy.util.XmlSlurper;

class XmlImportService{

	def dataDef;

	public void importData(String path) {

		getFileContent(path);
		importSkills();
		importPeriods();
		importPersons();
		importPersonSkills();
		importPersonPeriods();
		importTasks();
		importTaskSkills();
		importTaskPeriods();
	}

	public void getFileContent(String path) {
		dataDef = new XmlSlurper().parse( new File(path) )
	}

	public void importPersons() {
		dataDef.persons.person.each{
			Person p = new Person(lastname:it.@lastname.text(), firstname:it.@firstname.text(), email:it.@email.text(), username:it.@username.text());
			p.validate();
			p.save();
			println("person : " + p.toString())
		}
	}


	public void importSkills() {

		dataDef.skills.skill.each{
			Skill s = new Skill(name:it.@name.text());
			s.validate();
			s.save();
			println("skill : " + s.toString())
		}
	}

	public void importPeriods() {

		dataDef.periods.period.each{
			Period a = new Period(name:it.@name.text());
			a.validate();
			a.save();
			println("period : " + a.toString())
		}
	}

	public void importTasks() {

		dataDef.tasks.task.each{
			Task t = new Task(name:it.@name.text());
			t.validate();
			t.save();
			println("task : " + t.toString())
		}
	}

	public void importPersonSkills() {
		dataDef.persons.person.each{pxml->
			Person p = Person.findByUsername(pxml.@username.text())

			pxml.skills.skill.each{
				p.addToSkills( Skill.findByName(it.text()))
				p.save();
				println("person ${p.toString()} has new skill : " + Skill.findByName(it.text().toString()))
			}
		}
	}

	public void importTaskSkills() {
		dataDef.tasks.task.each{txml->
			Task t = Task.findByName(txml.@name.text())

			txml.skills.skill.each{
				t.addToSkills( Skill.findByName(it.text()))
				t.save();
				println("task ${t.toString()} has new skill : " + Skill.findByName(it.text().toString()))
			}
		}
	}
	
	public void importPersonPeriods() {
		dataDef.persons.person.each{pxml->
			Person p = Person.findByUsername(pxml.@username.text())

			pxml.periods.period.each{
				p.addToPeriods( Period.findByName(it.text()))
				p.save();
				println("person ${p.toString()} has new period : " + Period.findByName(it.text().toString()))
			}
		}
	}

	public void importTaskPeriods() {
		dataDef.tasks.task.each{txml->
			Task t = Task.findByName(txml.@name.text())

			txml.periods.period.each{
				t.addToPeriods( Period.findByName(it.text()))
				t.save();
				println("task ${t.toString()} has new period : " + Period.findByName(it.text().toString()))
			}
		}
	}
}